<template>
  <div class="content-table">
    <vxe-table
      ref="tableRef"
      :data="records"
      :height="height"
      :column-config="columnConfig"
      :row-config="rowConfig"
      :empty-text="emptyText"
      :loading="loading"
      :menu-config="menuConfig"
      @checkbox-all="selectAllChangeEvent"
      @checkbox-change="selectChangeEvent"
      @menu-click="contextMenuClickEvent"
    >
      <vxe-column type="checkbox" width="60"></vxe-column>
      <vxe-column type="expand" width="80" title="详细">
        <template #content="{ row }">
          <div class="expand-wrapper h-300px">
            <MonacoView :value="row['_source']" />
          </div>
        </template>
      </vxe-column>
      <vxe-column
        v-for="column in columns"
        :key="column.title"
        :field="column.field"
        :title="column.title"
        :fixed="renderFixed(column.title)"
        :visible="column.show"
        :width="Math.max(column.title.length * 14, 80)"
        show-overflow="tooltip"
      />
    </vxe-table>
  </div>
</template>
<script lang="ts" setup>
import { VxeTableInstance } from "vxe-table";
import { useUrlStore } from "@/store";
import { UseDataBrowserInstance } from "@/hooks";
import MonacoView from "@/components/view/MonacoView/index.vue";
import {
  buildContextMenuClickEvent,
  buildSelectAllChangeEvent,
  buildSelectChangeEvent
} from "@/page/data-browse/component/DbContainer/func";
import { columnConfig, menuConfig, rowConfig } from "@/page/data-browse/component/DbContainer/args";

const size = useWindowSize();

const props = defineProps({
  tab: {
    type: Object as PropType<UseDataBrowserInstance>,
    required: true
  }
});

const { index, selectedKeys, loading, records, columns } = props.tab as UseDataBrowserInstance;

const tableRef = ref<VxeTableInstance | null>(null);

const height = computed(() => size.height.value - 40 - 20 - 26 - 35);
const emptyText = computed(() => {
  if (!useUrlStore().url) {
    return "请先选择链接";
  }
  if (!index.value) {
    return "请在右上角选择索引";
  }
  return "什么也没有";
});

function renderFixed(title: string) {
  return title === "_id" ? "left" : null;
}

onMounted(() => {
  tableRef.value?.setCheckboxRow(selectedKeys.value, true);
});

// 全选事件
const selectAllChangeEvent = buildSelectAllChangeEvent(tableRef, props.tab);
// 选择事件
const selectChangeEvent = buildSelectChangeEvent(tableRef, props.tab);
// 菜单点击事件
const contextMenuClickEvent = buildContextMenuClickEvent(tableRef, props.tab);
</script>
<style scoped></style>
